<script setup name="stafflist">
import OAMain from '@/components/OAMain.vue';
import OADialog from '@/components/OADialog.vue';
import { ref, onMounted, watch } from "vue"
import staffHttp from '@/api/staffHttp';
import { ElMessage } from 'element-plus';
import timeFormat from '@/utils/timeFormat';
import { Edit, Search, Download, Upload } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth';


const authStore = useAuthStore()
const dialogVisible = ref(false)
const informs = ref([])
const list_ref = ref(null)
const pagination = ref({
    total: 0,
    page: 1,
    size: 10
})
const department_list = ref([])
const user_select_item = ref({
    department: null,
    name: "",
    time: []
})
const user_active = ref({
    1: "已激活",
    2: "未激活",
    3: "已锁定"
})
const type_color = ref({
    1: "success",
    2: "warning",
    3: "danger"
})

const user_status_value = ref(null)
const user_row_id = ref(null)
const user_row_index = ref(null)
const BASE_URL = import.meta.env.VITE_BASE_URL
const select_options = [
    {
        value: 1,
        label: '已激活',
    },
    {
        value: 2,
        label: '未激活',
    },
    {
        value: 3,
        label: '已锁定',
    }
]

const onSubmit = async () => {
    try {
        await staffHttp.updateStaffStatus(user_row_id.value, user_status_value.value)
        informs.value[user_row_index.value].status = user_status_value.value
        dialogVisible.value = false
        ElMessage.success('修改成功')
    } catch (err) {
        ElMessage.error(err.response?.data?.message || err.message)
    }
}

const handleSizeChange = () => {
    pagination.value.page = 1
    send_http(pagination.value.page, pagination.value.size)
}

const handleCurrentChange = async () => {
    send_http(pagination.value.page, pagination.value.size)
}

const handleEdit = (index, row) => {
    dialogVisible.value = true
    user_status_value.value = row.status
    user_row_id.value = row.uid
    user_row_index.value = index
}

const send_http = async (page, size) => {
    try {
        let res = await staffHttp.getStaffList(page, size, user_select_item.value)
        informs.value = res.results
        pagination.value.total = res.count
        pagination.value.page = page
    } catch (err) {
        console.error('完整错误对象:', err)
        console.log('响应数据:', err.response?.data)
        ElMessage.error(err.response?.data?.message || err.message)
    }
}

const onSearch = () => {
    send_http(1, pagination.value.size)
}
const onUploadSuccess = () => {
    ElMessage.success('员工上传成功')
    send_http(1, pagination.value.size)
}
const onUploadFail = (error) => {
    const detail = JSON.parse(error.message).detail
    ElMessage.error(detail)
}

const onDownload = async () => {
    let rows = list_ref.value.getSelectionRows()
    console.log("rows", rows)
    if (!rows || rows.length == 0) {
        ElMessage.info("请勾选要下载的数据")
        return
    }
    try {
        let res = await staffHttp.downloadStaffs(rows.map(row => row.uid))
        let href = URL.createObjectURL(res.data)
        const a = document.createElement("a")
        a.href = href
        a.setAttribute('download', '员工信息.xlsx')
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(href)
    } catch (error) {
        ElMessage.error(error)
    }
}
// }
onMounted(async () => {
    try {
        send_http()
        let res = await staffHttp.getAllDepartment()
        department_list.value = res.results
    } catch (err) {
        console.error('完整错误对象:', err)
        ElMessage.error(err.response?.data?.message || err.message)
    }
})

</script>


<template>
    <OADialog title="修改员工状态" v-model="dialogVisible" @submit="onSubmit">
        <el-select v-model="user_status_value" class="m-2" placeholder="修改员工状态" size="large">
            <el-option v-for="item in select_options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
    </OADialog>

    <OAMain title="员工列表">
        <el-card class="card_title">
            <el-form :inline="true">
                <el-form-item label="按部门">
                    <el-select v-model="user_select_item.department" style="min-width: 120px">
                        <el-option :label="item.name" :value="item.id" v-for="item in department_list" :key="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="按姓名">
                    <el-input v-model="user_select_item.name" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="按入职时间">
                    <el-date-picker v-model="user_select_item.time" type="daterange" range-separator="到"
                        start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="Search" type="primary" @click="onSearch" />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="Download" type="danger" @click="onDownload">下载</el-button>
                </el-form-item>
                <el-form-item>
                    <el-upload 
                        :action="BASE_URL+'/staff/upload'" 
                        :headers="{Authorization: 'JWT '+authStore.token}"
                        :on-success="onUploadSuccess"
                        :on-error="onUploadFail"
                        :show-file-list="false" 
                        :auto-upload="true"
                        accept=".xlsx, .xls">
                        <el-button :icon="Upload" type="danger">上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="list_card">
            <el-table :data="informs" ref="list_ref" style="width: 100%" class="yuangong_list">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" align="center" width="55">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="姓名" align="center" width="150">
                    <template #default="scope">
                        {{ scope.row.realname }}
                    </template>
                </el-table-column>
                <el-table-column label="邮箱" align="center">
                    <template #default="scope">
                        {{ scope.row.email }}
                    </template>
                </el-table-column>
                <el-table-column label="入职时间" align="center">
                    <template #default="scope">
                        {{ timeFormat.stringFromDateTime(scope.row.date_joined) }}
                    </template>
                </el-table-column>
                <el-table-column label="部门" align="center" width="150">
                    <template #default="scope">
                        {{ scope.row.department.name }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" width="150">
                    <template #default="scope">
                        <el-button :type="type_color[scope.row.status]" plain>{{ user_active[scope.row.status]
                        }}</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150">
                    <template #default="scope">
                        <el-button :icon="Edit" circle size="large" type="primary"
                            @click="handleEdit(scope.$index, scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </OAMain>
    <div class="fenye">
        <div></div>
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
            :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next" :total="pagination.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
</template>

<style scoped>
.card_title {
    margin-top: 20px;
}


.list_card {
    margin-top: 20px;
}

.fenye {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    margin-right: 50px;
}
</style>